<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">




  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Databinding,Jetpack,">





  <link rel="alternate" href="/atom.xml" title="Colin's Blog" type="application/atom+xml">






<meta name="description" content="声明： 本文翻译自Medium 文章  数据绑定库在 Android 应用程序的生产中越来越受欢迎，因为它扩大了 MVVM 架构的优势。它允许您使用声明性格式而不是以编程方式将布局中的UI组件绑定到应用程序中的数据源。自动通知UI关于数据的变化并获得传播回来的UI属性的变化，这不是很好吗？那么让我们看看我们如何通过单向和双向绑定绑定到 LiveData ！ 为什么绑定到 LiveData？使用">
<meta name="keywords" content="Databinding,Jetpack">
<meta property="og:type" content="article">
<meta property="og:title" content="[译] 高级 DataBinding: 绑定到 LiveData (单向绑定 &amp; 双向绑定) ">
<meta property="og:url" content="http://duanyitao.com/2019/04/22/译-高级-DataBinding-绑定到-LiveData-单向绑定-双向绑定/index.html">
<meta property="og:site_name" content="Colin&#39;s Blog">
<meta property="og:description" content="声明： 本文翻译自Medium 文章  数据绑定库在 Android 应用程序的生产中越来越受欢迎，因为它扩大了 MVVM 架构的优势。它允许您使用声明性格式而不是以编程方式将布局中的UI组件绑定到应用程序中的数据源。自动通知UI关于数据的变化并获得传播回来的UI属性的变化，这不是很好吗？那么让我们看看我们如何通过单向和双向绑定绑定到 LiveData ！ 为什么绑定到 LiveData？使用">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-22T05:53:35.929Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[译] 高级 DataBinding: 绑定到 LiveData (单向绑定 &amp; 双向绑定) ">
<meta name="twitter:description" content="声明： 本文翻译自Medium 文章  数据绑定库在 Android 应用程序的生产中越来越受欢迎，因为它扩大了 MVVM 架构的优势。它允许您使用声明性格式而不是以编程方式将布局中的UI组件绑定到应用程序中的数据源。自动通知UI关于数据的变化并获得传播回来的UI属性的变化，这不是很好吗？那么让我们看看我们如何通过单向和双向绑定绑定到 LiveData ！ 为什么绑定到 LiveData？使用">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":20,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://duanyitao.com/2019/04/22/译-高级-DataBinding-绑定到-LiveData-单向绑定-双向绑定/">





  <title>[译] 高级 DataBinding: 绑定到 LiveData (单向绑定 & 双向绑定)  | Colin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Colin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">时间是没有声音的锉刀。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-android">
          <a href="/categories/Android/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-android"></i> <br>
            
            Android
          </a>
        </li>
      
        
        <li class="menu-item menu-item-kotlin">
          <a href="/categories/Kotlin/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            Kotlin
          </a>
        </li>
      
        
        <li class="menu-item menu-item-dart">
          <a href="/categories/Dart/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-terminal"></i> <br>
            
            Dart
          </a>
        </li>
      
        
        <li class="menu-item menu-item-flutter">
          <a href="/categories/Flutter/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-road"></i> <br>
            
            Flutter
          </a>
        </li>
      
        
        <li class="menu-item menu-item-ios">
          <a href="/categories/iOS/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-apple"></i> <br>
            
            iOS
          </a>
        </li>
      
        
        <li class="menu-item menu-item-web">
          <a href="/categories/Web/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-html5"></i> <br>
            
            Web
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vim">
          <a href="/categories/Vim/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            Vim
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://duanyitao.com/2019/04/22/译-高级-DataBinding-绑定到-LiveData-单向绑定-双向绑定/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="段燚涛">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Colin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">[译] 高级 DataBinding: 绑定到 LiveData (单向绑定 & 双向绑定) </h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-22T11:13:13+08:00">
                2019-04-22
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-04-22T13:53:35+08:00">
                2019-04-22
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <blockquote>
<p>声明： 本文翻译自<a href="https://proandroiddev.com/advanced-data-binding-binding-to-livedata-one-and-two-way-binding-dae1cd68530f?gi=bd0854b80012" target="_blank" rel="noopener">Medium 文章</a></p>
</blockquote>
<p>数据绑定库在 Android 应用程序的生产中越来越受欢迎，因为它扩大了 MVVM 架构的优势。它允许您使用声明性格式而不是以编程方式将布局中的UI组件绑定到应用程序中的数据源。自动通知UI关于数据的变化并获得传播回来的UI属性的变化，这不是很好吗？那么让我们看看我们如何通过单向和双向绑定绑定到 LiveData ！</p>
<h2 id="为什么绑定到-LiveData？"><a href="#为什么绑定到-LiveData？" class="headerlink" title="为什么绑定到 LiveData？"></a>为什么绑定到 LiveData？</h2><p>使用生命周期感知组件（如LiveData）的优点包括：</p>
<ul>
<li><p>没有因停止活动而崩溃。如果观察者的生命周期处于非活动状态，例如活动位于后台堆栈中，则它不会收到任何 LiveData 事件。</p>
</li>
<li><p>自适应的配置更改。如果由于配置更改（例如，设备旋转）而重新创建 Fragment 或 Activity ，则会立即接收最新的可用数据。</p>
</li>
<li><p>没有内存泄漏。无需手动处理订阅。当相关的生命周期被破坏时，观察者会自行清理。</p>
</li>
</ul>
<h2 id="LiveData-VS-ObservableFields"><a href="#LiveData-VS-ObservableFields" class="headerlink" title="LiveData VS ObservableFields"></a>LiveData VS ObservableFields</h2><p>与实现 Observable 的对象 （例如可观察字段）不同  ，  LiveData 对象知道订阅数据更改的观察者的生命周期。无论 LiveData 和 ObservableFields， 他们都可以实现其观察数据变化，但是在其他方面，LiveData 有它特殊的优势：</p>
<ul>
<li><p>手动生命周期处理。UI组件只是观察相关数据，不会停止或恢复观察。LiveData 自动管理所有这些，因为它在观察时意识到相关的生命周期状态变化。</p>
</li>
<li><p>Transformations 和 MediatorLiveData 的更多功能。使用 LiveData 将使您受益于转换的强大功能，并且还可以向 MediatorLiveData 添加多个源。因此，如果布局中有5个 EditText 视图，则无需从 Activity 或 Fragment 中观察全部 5个 视图。您只能观察一个 MediatorLiveData，这将为您节省一些代码和逻辑复杂性。</p>
</li>
<li><p>共享资源。创建扩展 LiveData 的自定义对象将允许您连接到系统服务一次，然后任何需要该资源的观察者只能观察该对象。</p>
</li>
</ul>
<h3 id="开始使用带数据绑定的-LiveData"><a href="#开始使用带数据绑定的-LiveData" class="headerlink" title="开始使用带数据绑定的 LiveData"></a>开始使用带数据绑定的 LiveData</h3><p>要将 LiveData 对象与绑定类一起使用，需要指定生命周期所有者以定义 LiveData 对象的范围。以下示例说明如何在实例化绑定类之后将活动设置为生命周期所有者：</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Inflate view and obtain an instance of the binding class.</span></span><br><span class="line"><span class="keyword">val</span> binding: MainBinding = DataBindingUtil.setContentView(<span class="keyword">this</span>, R.layout.main)</span><br><span class="line"><span class="comment">// Specify the current activity as the lifecycle owner.</span></span><br><span class="line">binding.setLifecycleOwner(<span class="keyword">this</span>)</span><br></pre></td></tr></table></figure>
<p>所以现在我们可以在布局文件 main.xml 中使用 LiveData 对象，如下所示，commentText 的值将设置到 text 属性上：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">android.support.design.widget.TextInputEditText</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:text</span>=<span class="string">"@&#123;viewModel.commentText&#125;"</span> /&gt;</span></span><br></pre></td></tr></table></figure>
<p>在某些情况下，在数据绑定中使用 LiveData 时，可能会出现警告“…是一个盒装字段但需要取消装箱以执行…”。这表示使用可空类型作为 LiveData 对象值。要禁止警告，建议使用原语（ ObservableInt 而不是 MutableLiveData<integer> ）或使用safeUnbox，如下所示：</integer></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">android:text="@&#123;safeUnbox(viewModel.commentText)&#125;"</span><br></pre></td></tr></table></figure>
<h2 id="实现双向绑定"><a href="#实现双向绑定" class="headerlink" title="实现双向绑定"></a>实现双向绑定</h2><p>在预期从 UI 更新 LiveData 值的情况下，双向绑定变得非常方便。在代码中访问它时，我们希望收到更新的值。为了能够做到这一点，我们将在绑定表达式的花括号之前添加“=”：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">android.support.design.widget.TextInputEditText</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:text</span>=<span class="string">"@=&#123;viewModel.commentText&#125;"</span> /&gt;</span></span><br></pre></td></tr></table></figure>
<p>现在，只要用户在屏幕上的视图中键入新文本，LiveData 对象就会更新，当访问其值时，我们将收到最新的更新。</p>
<h2 id="创建自定义绑定适配器"><a href="#创建自定义绑定适配器" class="headerlink" title="创建自定义绑定适配器"></a>创建自定义绑定适配器</h2><p>为了更进一步，让我们想一个不那么通用的案例。想象一下，我们希望通过使用 LiveData 对象的数据绑定在 ViewPager 中设置当前选项卡。为此，我们需要在 BindingAdapter 的帮助下为 ViewPager 创建自定义属性 currentTab ：</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">   <span class="meta">@BindingAdapter(<span class="meta-string">"currentTab"</span>)</span></span><br><span class="line">   <span class="meta">@JvmStatic</span> </span><br><span class="line">   <span class="function"><span class="keyword">fun</span> <span class="title">setNewTab</span><span class="params">(pager: <span class="type">ViewPager</span>, newTab: <span class="type">MutableLiveData</span>&lt;<span class="type">Int</span>&gt;)</span></span> &#123;</span><br><span class="line">       newTab.value?.let &#123;</span><br><span class="line">          <span class="comment">//don't forget to break possible infinite loops!</span></span><br><span class="line">          <span class="keyword">if</span> (pager.currentItem != itemLiveData.value) &#123;       </span><br><span class="line">              pager.setCurrentItem(newTab.value, <span class="literal">true</span>)</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所以现在我们可以将新属性添加到布局文件中，并从 LiveData 对象值设置 ViewPager 的当前项：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">android.support.v4.view.ViewPager</span></span></span><br><span class="line"><span class="tag">    <span class="attr">app:currentTab</span>=<span class="string">"@&#123;viewModel.pagerCurrentTab&#125;"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p>当新值设置为 pagerCurrentTab 对象时，将执行 BindingAdapter 正文中的代码。</p>
<h2 id="使用自定义属性的双向绑定"><a href="#使用自定义属性的双向绑定" class="headerlink" title="使用自定义属性的双向绑定"></a>使用自定义属性的双向绑定</h2><p>现在，在更新我们创建的 LivaData 对象中的值时，ViewPager 会滚动到新位置。这很好，除了在我们的用例中，用户还与 UI 交互并更改ViewPager 的位置，但 LiveData 对象仍保留“旧”值。我们希望收到有关此属性更改的通知，以便基于它实现某些逻辑或只检查当前值。这可以通过实现双向绑定来实现。</p>
<p>我们将要对布局文件进行以下更改：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">android.support.v4.view.ViewPager</span></span></span><br><span class="line"><span class="tag">    <span class="attr">app:currentTab</span>=<span class="string">"@=&#123;viewModel.pagerCurrentTab&#125;"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p>BindingAdapter我们已经有了，另外需要创建一个 InverseBindingAdapter。此时，数据绑定知道在数据更改时要做什么（它调用使用了 @BindingAdapter 注释的方法）以及在 view 属性更改时调用的内容（它调用使用了 InverseBindingListener 注释的方法）。因此，如果用户滑动 ViewPager 选项卡，LiveData 对象将使用新值进行更新。但是，为了知道属性何时或如何更改，我们引入了自定义事件。事件的命名默认为具有后缀“AttrChanged”的属性名称。在这个场景里就是 currentTabAttrChanged。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">   <span class="meta">@BindingAdapter(<span class="meta-string">"currentTab"</span>)</span></span><br><span class="line">   <span class="meta">@JvmStatic</span> </span><br><span class="line">   <span class="function"><span class="keyword">fun</span> <span class="title">setTab</span><span class="params">(pager: <span class="type">ViewPager</span>, itemLiveData: <span class="type">MutableLiveData</span>&lt;<span class="type">Int</span>&gt;)</span></span>&#123;</span><br><span class="line">       itemLiveData.value?.let &#123; </span><br><span class="line">          <span class="comment">//don't forget to break possible infinite loops!</span></span><br><span class="line">          <span class="keyword">if</span> (pager.currentItem != itemLiveData.value) &#123;      </span><br><span class="line">              pager.setCurrentItem(itemLiveData.value, <span class="literal">true</span>)</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">    <span class="meta">@InverseBindingAdapter(attribute = <span class="meta-string">"currentTab"</span>, event =                     <span class="meta-string">"currentTabAttrChanged"</span>)</span></span><br><span class="line">    <span class="meta">@JvmStatic</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">getTab</span><span class="params">(pager: <span class="type">ViewPager</span>)</span></span> = pager.currentItem</span><br></pre></td></tr></table></figure>
<h2 id="一句警告"><a href="#一句警告" class="headerlink" title="一句警告"></a>一句警告</h2><p>使用双向数据绑定时，请注意不要引入无限循环。当用户更改属性时，将调用注释@InverseBindingAdapter 的方法。反过来，这将调用注释 @BindingAdapter 的方法，这将触发对注释 @InverseBindingAdapter 的方法的另一个调用，依此类推。</p>
<p>因此，通过比较注释 @BindingAdapter 的方法中的新旧值来打破可能的无限循环非常重要。</p>
<h2 id="一些最后的想法"><a href="#一些最后的想法" class="headerlink" title="一些最后的想法"></a>一些最后的想法</h2><p>Android 组件的生命周期很复杂，手动管理可能很麻烦，因为保持 UI 与数据源保持同步，因此引入 LiveData 是生命周期管理中的一大步。将数据绑定添加到项目中可以使代码更加简洁和反应，因为数据源中的更改可以自动传播到 UI，同时考虑了到配置和生命周期状态。但是，使用数据绑定库不应仅限于将数据模型的属性设置为文本字段。使用单向和双向绑定绑定到 LiveData 将允许您充分利用 Observer 模式和生命周期感知。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>============ END ============</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="段燚涛 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="段燚涛 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Databinding/" rel="tag"># Databinding</a>
          
            <a href="/tags/Jetpack/" rel="tag"># Jetpack</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/12/Jetpack-之-MVVM/" rel="next" title="Jetpack 之 MVVM">
                <i class="fa fa-chevron-left"></i> Jetpack 之 MVVM
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/23/Groovy-Syntax/" rel="prev" title="Groovy Syntax">
                Groovy Syntax <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MzUzNC8yMDA3Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="段燚涛">
            
              <p class="site-author-name" itemprop="name">段燚涛</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/duanyitao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:duanyitao7937@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                快速链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding/todoapp" title="Android-architecture" target="_blank">Android-architecture</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://developer.android.google.cn/jetpack" title="Jetpack" target="_blank">Jetpack</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么绑定到-LiveData？"><span class="nav-number">1.</span> <span class="nav-text">为什么绑定到 LiveData？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LiveData-VS-ObservableFields"><span class="nav-number">2.</span> <span class="nav-text">LiveData VS ObservableFields</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#开始使用带数据绑定的-LiveData"><span class="nav-number">2.1.</span> <span class="nav-text">开始使用带数据绑定的 LiveData</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现双向绑定"><span class="nav-number">3.</span> <span class="nav-text">实现双向绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建自定义绑定适配器"><span class="nav-number">4.</span> <span class="nav-text">创建自定义绑定适配器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用自定义属性的双向绑定"><span class="nav-number">5.</span> <span class="nav-text">使用自定义属性的双向绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一句警告"><span class="nav-number">6.</span> <span class="nav-text">一句警告</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一些最后的想法"><span class="nav-number">7.</span> <span class="nav-text">一些最后的想法</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Build by duanyitao.</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">38.6k</span>
  
</div>









        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
